package 计算BMI指数;

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;

public class TestClient extends Application {
    public static void main(String[] args) {
        launch(args);
    }


    DataOutputStream toServer = null;
    DataInputStream fromServer = null;
    @Override
    public void start(Stage primaryStage) {

        BorderPane paneForTextField = new BorderPane();
        paneForTextField.setPadding(new Insets(5, 5, 5, 5));
        paneForTextField.setStyle("-fx-border-color: green");
        paneForTextField.setLeft(new Label("Enter a weight: "));
        TextField tf = new TextField();
        tf.setAlignment(Pos.BOTTOM_RIGHT);
        paneForTextField.setCenter(tf);

        BorderPane mainPane = new BorderPane();
        TextArea ta = new TextArea();
        mainPane.setCenter(new ScrollPane(ta));
        mainPane.setTop(paneForTextField);

        Scene scene = new Scene(mainPane, 450, 200);
        primaryStage.setTitle("TestClient");  // Set the stage title  设置舞台标题
        primaryStage.setScene(scene);  // Place the scene in the stage  将场景放置在舞台上
        primaryStage.show();  // Display the stage 展示舞台

        tf.setOnAction(e -> {
            try {
                double weight = Double.parseDouble(tf.getText().trim());
                double height = Double.parseDouble(tf.getText().trim());

                toServer.writeDouble(weight);
                toServer.flush();
                double area1 = fromServer.readDouble();
                // Display to the text area  显示到文本区域
                ta.appendText("Weight is " + weight + "\n");
                ta.appendText("Area received from the server is "
                        + area1 + '\n');

            }catch (IOException ex){
                System.out.println(ex);
            }
        });

        try {
            // Create a socket to connect to the server  创建一个套接字以连接到服务器
            Socket socket = new Socket("localhost", 8000);
            fromServer = new DataInputStream(socket.getInputStream());
            // Create an output stream to receive data from the server  创建输出流以从服务器接收数据
            toServer = new DataOutputStream(socket.getOutputStream());
        } catch (IOException ex) {
            ta.appendText(ex.toString() + '\n');
        }

    }

}
